package cn.yuhao.party.school.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.jdbc.TxQueryRunner;
import cn.yuhao.party.pager.PageBean;
import cn.yuhao.party.pager.PageConstants;
import cn.yuhao.party.school.domain.School;

public class InschoolDao {
	private QueryRunner qr = new TxQueryRunner();

	
	public PageBean<School> findAll(int pc) {
		int ps = PageConstants.BOOK_PAGE_SIZE;// 每页记录数
		String sql = "select * from inschool limit ?,?";
		try {
			String sql1 = "select count(*) from inschool";
			Number number = (Number) qr.query(sql1, new ScalarHandler());
			int tr = number.intValue();// 得到了总记录数
			List<School> listSchool = qr.query(sql,
					new BeanListHandler<School>(School.class), (pc - 1) * ps,
					ps);
			PageBean<School> pb = new PageBean<School>();
			/*
			 * 其中PageBean没有url，这个任务由Servlet完成
			 */
			pb.setBeanList(listSchool);
			pb.setPc(pc);
			pb.setPs(ps);
			pb.setTr(tr);

			return pb;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public School findById(String Gtheme) {
		String sql = "select * from inschool where Gtheme=?";

		try {
			School school = (School) qr.query(sql, new BeanHandler<School>(
					School.class), Gtheme);
			return school;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void addSchool(School school) {
		String sql = "insert into inschool values(?,?,?,?,?,?,?,?,?)";
		Object[] params = { school.getGtheme(), school.getGpart(),
				school.getGtime(), school.getGcontent(), school.getGusername(),
				school.getGperson(), school.getGremain(), 
				school.getGplace() ,school.getGtupian()};
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void delete(String Gtheme) {
		String sql = "delete from inschool where Gtheme=?";
		try {
			qr.update(sql, Gtheme);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public void editSchool(School school) {
		String sql = "update inschool set Gpart=? ,Gtime=? ,Gcontent=? ,Gusername=?,Gperson=?,Gremain=?,Gplace=? ,Gtupian=? where Gtheme=?";
		Object[] params = { school.getGpart(), school.getGtime(),
				school.getGcontent(), school.getGusername(),
				school.getGperson(), school.getGremain(), school.getGplace(),
				school.getGtupian(), school.getGtheme() };
		try {
			qr.update(sql, params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
}
